export class WebSocketHelper {
  static socket: WebSocket
  static url: string
  static onOpen: any
  static onMessage: any
  static onError: any
  static onClose: any

  static connect(url: string, onOpen: any, onMessage: any, onError?: any, onClose?: any) {
    this.url = url
    this.onOpen = onOpen
    this.onMessage = onMessage
    this.onError = onError
    this.onClose = onClose
    this._connect()
  }

  static reconnect() {
    this._connect()
  }

  private static _connect() {
    if (this.socket) {
      this.socket.close();
    }
    this.socket = new WebSocket(this.url);
    this.socket.binaryType = 'arraybuffer';
    this.socket.onopen = () => {
      console.log('[WS] opened.');
      this.onOpen?.()
    }
    this.socket.onmessage = (e) => {
      console.log('[WS] receive: ', e.data);
      this.onMessage?.(e.data)
    }
    this.socket.onerror = (e) => {
      console.error('[WS] error: ', e);
      this.onError?.(e)
    }
    this.socket.onclose = () => {
      console.log('[WS] closed.');
      this.onClose?.()
    }
  }

  static send(msg: any) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      const msgStr = JSON.stringify(msg);
      console.log('[WS] sending msg: ', msgStr);
      this.socket.send(msgStr);
    } else {
      console.error('[WS]  not connected.');
    }
  }

  static isConnected() {
    return this.socket && this.socket.readyState === WebSocket.OPEN;
  }

  static close() {
    this.socket.close();
  }
}